'use strict';
const db = uniCloud.database();

exports.main = async (event, context) => {
  console.log('【markNotificationRead】云函数被调用，event：', event);

  const { notificationId, userId } = event;

  if (!notificationId || !userId) {
    return { success: false, message: '参数缺失' };
  }

  try {
    // 先检查通知是否存在且属于当前用户
    const notificationRes = await db.collection('notification-messages')
      .doc(notificationId)
      .get();
    
    if (!notificationRes.data || notificationRes.data.length === 0) {
      return { success: false, message: '通知不存在' };
    }
    
    const notification = notificationRes.data[0];
    if (notification.user_id !== userId) {
      return { success: false, message: '无权操作此通知' };
    }
    
    // 更新通知为已读状态
    const result = await db.collection('notification-messages')
      .doc(notificationId)
      .update({
        is_read: true,
        read_time: Date.now()
      });
    
    console.log('【markNotificationRead】更新结果：', result);

    return { 
      success: true, 
      message: '通知已标记为已读', 
      data: result 
    };

  } catch (e) {
    console.error('【markNotificationRead】异常:', e);
    return { success: false, message: '标记失败：' + e.message };
  }
}; 